package com.wang.listener;

import com.rabbitmq.client.Channel;
import com.wang.mapper.ProductMapper;
import com.wang.model.ProductMessage;
import com.wang.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@RabbitListener(queues =  "${mqconfig.stock_release_queue}")
@Component
@Slf4j
public class ProductStockMQListener {
    @Autowired
    private ProductService productService;

    /**
     * 监听库存释放消息      释放商品库存
     * @param productMessage
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void releaseStock(ProductMessage productMessage, Message message, Channel channel) throws IOException{
        log.info("监听到的消息为：{}",message);
        long msgTag = message.getMessageProperties().getDeliveryTag();

        boolean flag = productService.releaseCouponRecord(productMessage);

        try {
            if (flag) {
                //确认消息消费成功
                channel.basicAck(msgTag, false);
            }else {
                //失败后（下面的异常也是一样），将消息重复发给死信队列，再次操作（这里要注意重复次数，不可能无限进行重复操作）
                log.error("释放商品库存失败 flag=false,{}",productMessage);
                channel.basicReject(msgTag,true);
            }

        } catch (IOException e) {
            log.error("释放商品库存异常:{},msg:{}",e,productMessage);
            channel.basicReject(msgTag,true);
        }
    }
}
